package com.example.studentmanagement.controller;

import com.example.studentmanagement.entity.Student;
import com.example.studentmanagement.service.ClassService;
import com.example.studentmanagement.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 〈功能概述〉<br>
 *
 * @className: StudentController
 * @author: 程序员Mars
 * @date: 2024/12/26 20:30
 */
@Controller
@RequestMapping("/student")
public class StudentController {

    @Autowired
    private StudentService studentService;


    @Autowired
    private ClassService classService;

    /**
     * 显示学生列表
     */
    @GetMapping("/list")
    public String listStudents(Model model) {
        List<Student> students = studentService.getAllStudents();
        model.addAttribute("students", students);
        return "student-list";
    }

    /**
     * 根据班级 ID 显示学生列表
     */
    @GetMapping("/list-by-class/{classId}")
    public String listStudentsByClass(@PathVariable("classId") Integer classId, Model model) {
        List<Student> students = studentService.getStudentsByClassId(classId);
        model.addAttribute("students", students);
        return "student-list";
    }

    /**
     * 跳转到新增学生页面
     */
    @GetMapping("/create")
    public String createStudentForm(Model model) {
        model.addAttribute("student", new Student());
        model.addAttribute("classes", classService.getAllClasses());
        return "student-form";
    }

    /**
     * 跳转到编辑学生页面
     */
    @GetMapping("/edit/{id}")
    public String editStudentForm(@PathVariable("id") Integer id, Model model) {
        Student student = studentService.getStudentById(id);
        model.addAttribute("student", student);
        model.addAttribute("classes", classService.getAllClasses());
        return "student-form";
    }

    /**
     * 保存或更新学生
     */
    @PostMapping("/save")
    public String saveStudent(@ModelAttribute Student student) {
        if (student.getId() == null) {
            studentService.createStudent(student); // 新增
        } else {
            studentService.updateStudent(student); // 更新
        }
        return "redirect:/student/list";
    }

    /**
     * 删除学生
     */
    @GetMapping("/delete/{id}")
    public String deleteStudent(@PathVariable("id") Integer id) {
        studentService.deleteStudent(id);
        return "redirect:/student/list";
    }

}